package com.itguigu.rabbitmq.eight;

import com.itguigu.rabbitmq.utils.RabbitMqutil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import jdk.nashorn.internal.objects.NativeNumber;
import sun.applet.Main;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Date 2021/7/19 10:01
 * @Created by wangle
 * @Description
 */
public class Consumer01 {
    public static final String exchangeName = "normal_exchange";
    public static final String exchangeName2 = "dead_exchange";
    public static final String queueName = "normal_queue";
    public static final String queueName2 = "dead_queue";

    public static void main(String[] args) throws IOException, TimeoutException {

        Channel channel = RabbitMqutil.getChannel();
        //声明交换机和队列
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(exchangeName2, BuiltinExchangeType.DIRECT);

        //参数
        Map<String, Object> arguments = new HashMap<>();
//        //1.过期时间
//        arguments.put("x-message-ttl",10000);
        // 2 正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange", exchangeName2);
        //设置死信routingkey
        arguments.put("x-dead-letter-routing-key", "lisi");
//        //正常队列的长度的限制
//        arguments.put("x-max-length",6);


        //普通队列
        channel.queueDeclare(queueName, false, false, false, arguments);

        /////////////////死信队列
        channel.queueDeclare(queueName2, false, false, false, null);

        //绑定普通的交换机和普通的队列
        channel.queueBind(queueName, exchangeName, "zhangsan");
        //绑定私信交换机和死信队列
        channel.queueBind(queueName2, exchangeName2, "lisi");


        //声明 接受消息
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody());

            if (msg.equals("info5")) {

                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
                System.out.println("consumer1拒绝接受的消息是：" + msg);
            } else {
                System.out.println("consumer1接受的消息是：" + msg);
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }


        };

        //取消消息时的回调
        CancelCallback cancelCallback = (consumerTag) -> {

            System.out.println("消息消费被中断");
        };
//        开启手动应答，拒绝消息
        channel.basicConsume(queueName, false, deliverCallback, cancelCallback);
        // channel.basicConsume(queueName,true,deliverCallback,cancelCallback);
    }


}
